package cn.itrip.trade.controller;

import cn.itrip.dto.Dto;
import cn.itrip.pojo.ItripHotelOrder;
import cn.itrip.trade.config.WXPayConfig;
import cn.itrip.trade.service.PayService;
import cn.itrip.utlis.DtoUtils;
import cn.itrip.trade.WXutils.WXPayRequest;
import cn.itrip.trade.WXutils.WXPayUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付接口
 */
@Controller
@RequestMapping(value = "/api/wxpay/")
public class WXPayController {
    @Resource
    private PayService payService;
    @Resource
    private WXPayConfig wXPayConfig;
    @Resource
    private PayService payServices;


    @ApiOperation(value = "订单微信支付", httpMethod = "GET",
            protocols = "HTTP", produces = "application/xml", consumes = "application/x-www-form-urlencoded",
            response = String.class,
            notes = "客户端提交订单支付请求，对该API的返回结果不用处理，浏览器将自动跳转至微信支付二维码页面。<br><b>请使用普通表单提交，不能使用ajax异步提交。</b>")
    @RequestMapping(value = "/createqccode/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto createQcCode(@PathVariable String orderNo, HttpServletResponse response) {
        //判断订单是否有效
        ItripHotelOrder order = null;
        try {
            order = payService.getHotelOrder(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail("訂單獲取失敗","2222551");
        }
        //创建统一下单工具类  进行数据封装
        WXPayRequest wxPayRequest = new WXPayRequest(this.wXPayConfig);
        HashMap<String, Object> result = new HashMap<String, Object>();
        Map<String,String> data = new HashMap<>();
        //訂單名稱
        data.put("body", "爱旅行项目订单支付");
        //訂單號
        data.put("out_trade_no", orderNo);
        //訂單信息
        data.put("device_info",order.getHotelname()+order.getRoomid());
        //總金額
        data.put("total_fee", "1");
        //ip地址
        data.put("spbill_create_ip", "47.92.146.135");
        //囘調地址
        data.put("notify_url", "http:///itrip.test.com/trade/api/wxpay/notify");
        try {
            //修改wxPayRequest類 使用方法封裝參數，調用請求，返回結果，轉換成Map
            //带上参数去请 求微信的url
            Map<String, String> respMap = wxPayRequest.unifiedorder(data);
            String codeUrl = null;
            if ("SUCCESS".equals(respMap.get("result_code"))) {
                //拿到请求的返回结果code_url
                codeUrl = respMap.get("code_url");
                //根据前台需求封装相应订单信息
                result.put("hotelName", order.getHotelname());
                result.put("roomId", order.getRoomid());
                result.put("count", order.getCount());
                result.put("payAmount", order.getPayamount());
                result.put("codeUrl", codeUrl);
                return DtoUtils.returnDataSuccess(result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return DtoUtils.returnFail("獲取失敗","1000010");
    }


    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> paymentCallBack(HttpServletRequest request, HttpServletResponse response) {
        //驗證簽名參數
        WXPayRequest wxPayRequest = new WXPayRequest(this.wXPayConfig);
        //結果
        Map<String, String> result = new HashMap<String, String>();
        Map<String, String> params = null;

        //讀取囘調的數據
        try {
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            //将回传数据转化为map
            params = WXPayUtil.xmlToMap(sb.toString());
            //判斷簽名是否正確
            boolean flag = wxPayRequest.isResponseSignatureValid(params);
            if (flag) {
                String returnCode = params.get("return_code");
                if (returnCode.equals("SUCCESS")) {
                    //業務處理
                    //獲取微信訂單號
                    String transactionId = params.get("transaction_id");
                    //獲取商戶訂單號
                    String outTradeNo = params.get("out_trade_no");
                    if (payServices.getHotelOrder(outTradeNo)!=null) {
                        //修改后台订单状态
                        payServices.modifierHotelOrder(outTradeNo, 2,transactionId);
                       //修改库存
                        payService.paySuccess(outTradeNo,2,outTradeNo);
                    }
                } else {
                    result.put("return_code", "FAIL");
                    result.put("return_msg", "支付失败");
                }
            } else {
                result.put("return_code", "FAIL");
                result.put("return_msg", "签名失败");
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return result;
    }
    /***
     * ww
     * 微信支付轮询订单，查看订单是否支付成功
     *
     * @param orderNo
     * @return
     */
    @ApiOperation(value = "订单微信支付刷单程序", httpMethod = "GET",
            protocols = "HTTP", produces = "application/xml", consumes = "application/x-www-form-urlencoded",
            response = String.class,
            notes = "前端用户检测订单是否成功的接口<br>如果订单状态为2则代表订单支付成功<b></b>")
    @RequestMapping(value = "/queryorderstatus/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto<ItripHotelOrder> queryOrderIsSuccess(@PathVariable String orderNo) {
        ItripHotelOrder order = null;
        try {
            //查询订单，返回前台判断支付结果
            order = payService.getHotelOrder(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtils.returnDataSuccess(order);
    }
}
